package com.example.openim.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;

/**
 * @description:
 * @author: zyc
 * @created: 2024-06-24 15:45
 */
public final class AesGcmUtil {

    public static void main(String[] args) throws IOException {
//        String s=encrypt("abc", MD5.create().digestHex("abc"));
//        String s=encrypt("abc", MD5Util.encrypt("abc"));
//        System.out.println("加密======》"+s);
        // EiwcUhxoDLB93sIrtCwaFzCLvLrWVVubCwP0stAa5g==
//        System.out.println(decrypt(s,MD5.create().digestHex("abc")));
//        System.out.println("解密======》"+decrypt(s,MD5Util.encrypt("abc")));

    }

    /**
     * 解密
     * */
    public static String decrypt(String base64Content, String encryptPass) {
        try {
            byte[] content = Base64Utils.decode(base64Content);
            byte[] sKey = Base64Utils.decode(encryptPass);
            if (content.length < 12 + 16) {
                throw new IllegalArgumentException();
            }
            GCMParameterSpec params = new GCMParameterSpec(128, content, 0, 12);
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKey key2 = new SecretKeySpec(sKey, "AES");
            cipher.init(Cipher.DECRYPT_MODE, key2, params);
            byte[] decryptData = cipher.doFinal(content, 12, content.length - 12);
            return new String(decryptData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密
     * */
    public static String encrypt(String content, String encryptPass) {
        try {
            byte[] sKey = Base64Utils.decode(encryptPass);
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKey key2 = new SecretKeySpec(sKey, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, key2);
            byte[] iv = cipher.getIV();
            String s=Base64Utils.encode(iv);
            assert iv.length == 12;
            byte[] encryptData = cipher.doFinal(content.getBytes());
            assert encryptData.length == content.getBytes().length + 16;
            byte[] message = new byte[12 + content.getBytes().length + 16];
            System.arraycopy(iv, 0, message, 0, 12);
            System.arraycopy(encryptData, 0, message, 12, encryptData.length);
            return Base64Utils.encode(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
